import { BaseService, CoolCommException } from "@cool-midway/core";
import { Inject, Provide } from "@midwayjs/core";
import { ProviderCertificateEntity, ProviderCertificateStatus } from "../entity/certificate";
import { Equal, Repository } from "typeorm";
import { InjectEntityModel } from "@midwayjs/typeorm";
import { AddCertificateDTO, AuditCertificateDTO } from "../dto/certificate";
import { Context } from "@midwayjs/koa";
import { ProviderInfoEntity } from "../entity/info";


@Provide()
export class ProviderCertificateService extends BaseService {

    @InjectEntityModel(ProviderCertificateEntity)
    providerCertificateModel: Repository<ProviderCertificateEntity>

    @InjectEntityModel(ProviderInfoEntity)
    providerInfoModel: Repository<ProviderInfoEntity>

    @Inject()
    ctx: Context

    // 服务人员端： 新增证件信息
    async add(dto: AddCertificateDTO) {
        // 判断是否添加过该类型的证件
        const exist = await this.providerCertificateModel.exists({
            where: { providerId: Equal(this.ctx.provider.id), type: dto.type },
        });
        if (exist) {
            throw new CoolCommException('已添加过该类型的证件');
        }

        const name = dto.data?.name;

        return this.providerCertificateModel.save({
            ...dto,
            name,
            providerId: this.ctx.provider.id,
            status: ProviderCertificateStatus.SUBMITTED
        });
    }

    // 服务人员端： 修改证件信息
    async update(dto: any) {
        const { id, data } = dto;
        const info = await this.providerCertificateModel.findOne({ where: { id, providerId: Equal(this.ctx.provider.id) } });
        if (!info) {
            throw new CoolCommException('证件不存在');
        }

        const name = data?.name;

        return this.providerCertificateModel.save({
            ...info,
            ...dto,
            name: name || info.name,
            status: ProviderCertificateStatus.SUBMITTED,
        });
    }

    // 管理员端： 审核证件信息
    async auditCertificate(dto: AuditCertificateDTO) {
        const { id, status, rejectReason } = dto;
        const certificate = await this.providerCertificateModel.findOne({ where: { id } });
        if (!certificate) {
            throw new CoolCommException('证件不存在');
        }
        return await this.providerCertificateModel.update(id, { status, rejectReason });
    }


    async getMyCertificate() {
        return await this.providerCertificateModel.find({
            where: { providerId: Equal(this.ctx.provider.id) },
        });
    }

    async getMyCertificateById(id: number) {
        return await this.providerCertificateModel.findOne({ where: { id, providerId: Equal(this.ctx.provider.id) } });
    }

    async getByProviderId(providerId: number) {
        return await this.providerCertificateModel.find({
            where: {
                providerId: Equal(providerId),
                status: ProviderCertificateStatus.PASSED
            }
        });
    }
}
